import DataSelect from '@/components/DataSelect';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { DictItemSelect, DictTreeSelect } from '@/components/biz';
import * as BASE from '@/stores/definitions-base';
import { Input, Message, NumberPicker, Switch } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';
import { getCities, getCompanies, searchStation } from './api';
import DataAutoComplete from '@/components/DataAutoComplete';

const {
  DATETIME_TEXT,
  DATE_TEXT,
  TIME_TEXT,
  EMPTY_TEXT,
  ENUMS: ENUMSBase,
  FieldsGrid: FieldGridBase,
  TitleGrid,
  column: columnBase,
  toSelectDataSource,
} = BASE;
export { DATETIME_TEXT, DATE_TEXT, EMPTY_TEXT, TIME_TEXT, TitleGrid, toSelectDataSource };

/**
 * @param {*} path        属性path
 * @param {*} props       column属性
 * @returns column定义
 */
export function column(...args) {
  return columnBase(dataModel, ...args);
}

/**
 * 显示一组表单字段
 * ```js
 * {
 *   fields: string[],    // 字段名称，可以使用.来指定嵌套对象属性，例如order.busOrder.shift
 *   columns: number,     // 列数，默认为4,最大为12,最小为1
 *   model: object,       // 字段定义数据模型的根对象，默认不指定，仅在使用子对象作为根模型时设置
 *   overrideModel: object, // 重载字段定义数据模型
 *   mode: string,        // 表单模式，默认为edit，可选view
 *   itemLayout: object,  // FormItem布局配置，默认为{}
 * }
 * ```
 *
 * @param {object} param0
 * @returns
 */
export function FieldsGrid(props) {
  return <FieldGridBase model={dataModel} {...props} />;
}

//----------------------------------------------------------------------
export const ENUMS = {
  ...ENUMSBase,
  state: {
    // 启用状态
    true: t`启用`,
    false: t`禁用`,
  },
  stationType: {
    // 站点类型
    0: t`普通站点`,
    1: t`换乘站点`,
  },
  types: {
    // 站点类型
    0: t`中港通`,
    1: t`自营`,
    2: t`拼车`,
  },
};

/**
 * 模型定义：
 * 1. 普通文本仅需要定义label
 * 2. 需要通过枚举转换的值，定义text; 当使用renderer返回组件时，text属性无效，需要通过组件的renderPreview来指定预览时的绘制方式
 * 3. 通用的ui属性需要定制时，定义ui; 特定模式(view, edit, add)下的ui，添加后缀定义为ui_<mode>，例如：ui_view, ui_edit, ui_add, ui_table
 * 4. ui可配置属性包括:
 *    renderer: 内容渲染函数, Form表单中的原型为：(value: any, formData: any, fieldDefinition: any) => ReactNode; Table Column中的原型为: (value: any, columnIndex: number, rowData: any) => ReactNode;
 *    itemProps: 表单Form.Item的属性，可以是对象，或函数({ isPreview: boolean, mode: string, value: any, formData: any, ...otherDefinitions}) => void;
 *    span: Grid Cell占用的列数, 默认为1
 *
 * 【注】获取接口的model定义后，vscode中通过正则替换：^(\s+)"label": "([^']+)"  ===> $1label: t`$2`
 */
export const dataModel = {
  id: {
    label: t`编号`,
  },
  name: {
    label: t`名称`,
    ui: {
      itemProps: { required: true },
    },
  },
  areaName: {
    label: t`行政区`,
  },
  disable: {
    label: t`是否启用`,
    ui: {
      renderer: (v) => <Switch checked={v} size="small" autoWidth checkedChildren={t`启用`} unCheckedChildren={t`禁用`} />,
    },
    ui_table: {
      renderer: (v, i, row) => (
        <Switch
          checked={v}
          size="small"
          autoWidth
          checkedChildren={t`启用`}
          unCheckedChildren={t`禁用`}
          onClick={() => rootStore.scStationStore.updateState(row)}
        />
      ),
    },
  },
  description: {
    label: t`描述`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} />,
      span: 2,
    },
  },
  address: {
    label: t`站点地址`,
    ui: {
      itemProps: { required: true },
    },
  },
  rsAddress: {
    label: t`拼车站点地址`,
  },
  city: {
    label: t`所属城市`,
    ui: {
      renderer: (v) => (
        <DataSelect onFetch={() => getCities({ type: '0' })} value={v} labelField="name" valueField="itemId" />
      ),
      itemProps: { required: true },
    },
  },
  cityText: {
    label: t`城市`,
  },
  longLat: {
    label: t`经纬度`,
    ui_table: {
      renderer: (v) => v && v.split(',').map((s) => <div key={s}>{s}</div>),
    },
  },
  rsLongLat: {
    label: t`拼车地址经纬度`,
    ui_table: {
      renderer: (v) => v && v.split(',').map((s) => <div key={s}>{s}</div>),
    },
  },
  siteMapping: {
    label: t`站点映射`,
    '{key}': {
      companyId: {
        label: t`运营公司`,
        ui: {
          renderer: (v) => (
            <DataSelect hasClear onFetch={() => getCompanies()} value={v} labelField="name" valueField="id" />
          ),
        },
      },
      stationId: {
        label: t`站点id`,
        ui: {
          renderer: (v, formData) => (
            <DataAutoComplete
              hasClear
              placeholder={t`请输入需要匹配的站点名称`}
              value={v}
              labelField="name"
              valueField="stationId"
              onFocus={() => {
                if (!formData.siteMapping?.companyId) {
                  Message.warning(t`请先设置运营公司`);
                }
              }}
              args={{ stations: [v] }}
              onFetch={(_, args) => {
                const { keyword } = args || {};
                return keyword ? searchStation({ keyword }) : searchStation(args);
              }}
            />
          ),
        },
      },
      longLat: {
        label: t`经纬度`,
      },
      description: {
        label: t`描述说明`,
      },
      link: {
        label: t`链接`,
      },
      address: {
        label: t`详细地址`,
      },
      attachments: [
        {
          label: t`附件`,
          title: {
            label: t`附件标题`,
          },
          description: {
            label: t`附件说明`,
          },
          binaryId: [
            {
              label: t`附件id`,
            },
          ],
        },
      ],
    },
  },
  link: {
    label: t`详情地址页面链接`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} />,
    },
  },
  rsLink: {
    label: t`拼车详情地址页面链接`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} />,
    },
  },
  attachments: [
    {
      label: t`附件`,
      title: {
        label: t`附件标题`,
      },
      description: {
        label: t`附件说明`,
      },
      binaryId: [
        {
          label: t`附件id`,
        },
      ],
    },
  ],
  rsAttachments: [
    {
      label: t`附件`,
      title: {
        label: t`附件标题`,
      },
      description: {
        label: t`附件说明`,
      },
      binaryId: [
        {
          label: t`附件id`,
        },
      ],
    },
  ],
  crBy: {
    label: t`创建者`,
  },
  upBy: {
    label: t`最后修改者`,
  },
  crDate: {
    label: t`创建时间`,
  },
  upDate: {
    label: t`最后修收时间`,
  },
  tenantId: {
    label: t`租户ID`,
  },
  types: {
    label: t`站点类型`,
    ui: {
      renderer: (v) => <TauSimpleSelect value={v} dataSource={toSelectDataSource(ENUMS.types)} mode="multiple" />,
    },
  },
};
